<template>
	<div class="box" style="background: #fff;padding: 10px;">
		<div class="empty" v-if='isShowEmpty' @click="selectTemplate">
			<p><van-icon name="plus" /></p>
			<p>请选择模板</p>
		</div>

		<div class="content" v-if='!isShowEmpty'>
			<RecursiveRenderer :data="createFileObj" @input-change="updateCreateFileObj" @addArray='addArray'
				@delArray='delArray'></RecursiveRenderer>
			<Title title='文件名'></Title>
			<van-field :value="createFileObj.remark" placeholder="请输入文件名" type="textarea" autosize :border="true"
				input-align="left" @change="changeInput($event, 'string' , 'remark')" />
		</div>



		<div class="btn_box" v-if='!isShowEmpty'>
			<button class="btn" @click="save">保存</button>
		</div>


	</div>
</template>

<script>
	import RecursiveRenderer from "./RecursiveRenderer.vue"
	import Title from "./Title.vue"
	export default {
		data() {
			return {
				createFileObj: {},
				isShowEmpty: true,
				pathFile: '',
				templateId: '',
				wordFileId: ''
			}
		},

		components: {
			RecursiveRenderer,
			Title
		},

		onLoad(option) {
			if (option.data) {
				this.getJsonString('update', JSON.parse(option.data))
			}
		},

		mounted() {
			uni.$on('refreshPreviousPage', (data) => {
				console.log(data, 'data');
				if (data.id) {
					this.getJsonString("add", data.id)
				}
			});
		},

		methods: {
			// 获取json数据
			async getJsonString(type, data) {
				if (type == 'add') {
					let result = await this.$axios('overallSituation', {
						state: 'look',
						databaseName: "templateManagement",
						_id: data
					}, true)
					if (result.code != 200) return
					this.$set(this, 'createFileObj', JSON.parse(result.data[0].jsonString))
					this.pathFile = result.data[0].url //远程地址
					this.templateId = result.data[0]._id
				} else {
					this.$set(this, 'createFileObj', data.dataJson)
					this.pathFile = data.templateUrl //远程地址
					this.templateId = data.templateId //远程地址
					this.wordFileId = data._id
				}
				this.isShowEmpty = false //关闭空状态
			},



			// 输入框内容发生变化
			changeInput(e, type, str, index) {
				console.log(e, type, str)
				// 判断是字符串
				if (type == 'string') {
					this.createFileObj[str] = e.detail
				} else if (Array.isArray(this.createFileObj[type])) {
					// 判断是数组
					this.createFileObj[type][index][str] = e.detail
				} else {
					// 都不满足 就是对象
					this.createFileObj[type][str] = e.detail
				}
			},

			addArray(e) {
				// 找到需要push的目标
				if (this.createFileObj[e.key]) {
					this.createFileObj[e.key].push(e.data)
				} else {
					// 如果找不到 那么有可能是存在某一个数组里面的一个小数组
					this.createFileObj[e.fatherKey][e.fatherIndex][e.key].push(e.data)
				}
				console.log(e, 'e');
			},

			delArray(e) {
				if (this.createFileObj[e.key]) {
					if (this.createFileObj[e.key].length > 1) {
						this.createFileObj[e.key].splice(e.index, 1)
					}
				} else {
					if (this.createFileObj[e.fatherKey][e.fatherIndex][e.key].length > 1) {
						this.createFileObj[e.fatherKey][e.fatherIndex][e.key].splice(e.index, 1)
					}
				}
			},

			// 保存
			async save() {
				uni.showLoading({
					title: "文件正在保存中",
				})
				let parmse = {
					state: 'add',
					databaseName: "wordFile",
					dataJson: this.createFileObj,
					templateUrl: this.pathFile,
					templateId: this.templateId,
					userName: uni.getStorageSync('userInfo').userName,
					createTime: this.getTime(),
					remark: this.createFileObj.remark
				}

				if (this.wordFileId) {
					// 修改
					parmse.state = 'update'
					parmse._id = this.wordFileId
				}

				// 生成文件远程地址
				let result = await this.$axios('getWordFile', {
					data: this.createFileObj,
					url: this.pathFile
				}, false)
				if (result.code == 200) {
					parmse.url = result.data
				} else {
					uni.showToast({
						title: '操作失败',
						icon: 'none',
						duration: 2000
					})
					return
				}

				// 保存当前文件
				let saveFile = await this.$axios('overallSituation', parmse, false)
				uni.hideLoading()
				uni.navigateBack({
					delta: 1
				})
			},

			getTime() {
				let date = new Date()
				let year = date.getFullYear()
				let month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)
				let day = date.getDate() >= 10 ? date.getDate() : '0' + (date.getDate())
				let h = date.getHours() >= 10 ? date.getHours() : '0' + (date.getHours())
				let m = date.getMinutes() >= 10 ? date.getMinutes() : '0' + (date.getMinutes())
				let s = date.getSeconds() >= 10 ? date.getSeconds() : '0' + (date.getSeconds())
				return year + '-' + month + '-' + day + " " + h + ":" + m + ":" + s
			},

			// 递归组件内容发生变化 数组稍微复杂
			updateCreateFileObj(e) {
				console.log(e, 'e');
				if (e.type == 'array') {
					let value = ''

					function recursion(object, str = '') {
						str += `${object.key}.${object.index}.`
						if (object.changes.type) {
							str = recursion(object.changes, str)
						} else {
							str += `${object.changes.key}`
							value = object.changes.value
						}
						return str
					}

					function setValueByPath(obj, path, value) {
						// 将路径字符串按点分隔成数组
						const pathParts = path.split('.');

						// 初始化当前访问的对象为传入的根对象
						let currentObj = obj;

						// 遍历路径数组，直到最后一个部分之前
						for (let i = 0; i < pathParts.length - 1; i++) {
							// 如果当前部分是数字，将其转换为整数类型（假设数组索引）
							const part = !isNaN(pathParts[i]) ? parseInt(pathParts[i], 10) : pathParts[i];

							// 检查当前对象是否有该属性，如果没有则创建它（这里只处理到缺失的最终层级的前一级）
							if (!currentObj.hasOwnProperty(part)) {
								// 注意：这里简单处理为创建对象属性，对于数组索引需要更复杂的逻辑
								// 这里假设除了最后一个部分外，前面的路径都是已存在的对象或数组
								// 如果需要自动创建数组索引，需要额外的逻辑来判断并处理
								console.warn(`Missing property ${part} in path ${path}`);
								return; // 或者可以抛出错误，或者根据需求创建空对象/数组
							}

							// 进入下一级对象或数组
							currentObj = currentObj[part];
						}

						// 最后一个部分是要赋值的属性名
						const lastName = pathParts[pathParts.length - 1];

						// 给最终属性赋值
						currentObj[lastName] = value;
					}

					setValueByPath(this.createFileObj, recursion(e), value);
					console.log(this.createFileObj, '123123');

				} else if (e.type == 'object') {
					this.createFileObj[e.key][e.changes.key] = e.changes.value
				} else {
					this.createFileObj[e.key] = e.value
				}
			},

			// 跳转选择模板页面
			selectTemplate() {
				this.$router("/subPackages2/pages/templateManagement/index?type=1")
			}
		}
	}
</script>

<style scoped>
	.empty {
		width: 100%;
		height: 95%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
	}

	.content {
		width: 100%;
		height: 95%;
		overflow-y: scroll;
	}

	.empty p:nth-child(1) {
		font-size: 1.4rem;
		font-weight: 700;
		color: #333;
	}

	.empty p:nth-child(2) {
		font-size: 12px;
		color: #666;
		margin-top: 10px;
	}

	.btn_box {
		width: 100%;
		height: 5%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.btn_box .btn {
		width: 95%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: 700;
		font-size: 12px;
		color: #fff;
		background: #1BA035;
	}
</style>